<template>

  <div id="myrightGroup">
         <x-header title="分类" style="position:fixed;top:0px;z-index:1000;width:100%" :left-options="{showBack: false}" @on-click-more="show = false"></x-header> 

  

    
      <flexbox v-if="isSearch == false" :gutter="0" wrap="wrap" class="contentWrap leftContent">
        <div  id="sets">
      <search
      @result-click="resultClick"
      @on-change="getResult"
      :results="results"
      v-model="value"
      cancel-text="取消"
      :autoFixed="true"
      auto-scroll-to-top top=""
      @on-focus="onFocus"
      @on-cancel="onCancel"
      @on-submit="onSubmit"
      ref="search" style="margin-top:46px"></search>
  </div>
        <flexbox-item  :span="1/4">
          <div class="flex-demo" >
            <scroller :height="myHeight" ref="leftScroller" class="leftScroll" lock-x scrollbar-y>
        
                <group>
                  <cell class="cells" :class="{classifyActive:i==currentLeftIndex}" v-for="(item, i) in leftData" :key="i" @click.native="onCellClick(item,i)" :title="item.name"></cell>
                </group>
              
            </scroller>
          </div>
          </flexbox-item>
        <!-- <flexbox-item :span="3/4">
          <div class="flex-demo"  >
            <scroller @on-scroll="onScroll" :height="myHeight" class="rightScroll" lock-x scrollbar-y ref="rightScroller">
              <div  class="box2" style="padding:0px 0.5rem">
                <group style="margin-top:0.5rem;" ref="myGroup" v-for="(item, i) in detailClassify" :key="i">
                  <img width="265"  src="http://img4.imgtn.bdimg.com/it/u=1091593375,2912850015&fm=27&gp=0.jpg" alt="">
                  <group-title ref="groupTitle" style="text-align:left">{{item.name}}</group-title>
                  <grid :cols="myCols" id="myGrid">
                    <grid-item  v-for="(classifyItem, index) in item.data" :key="index" :icon="getSanJiImg(classifyItem.image)">
                    </grid-item>
                  </grid>
                </group>
              </div>
            </scroller>
          </div>
        </flexbox-item> -->
        <!-- ........ -->
        
         <flexbox-item :span="3/4">
          <div class="flex-demo"  >
            <scroller @on-scroll="onScroll" :height="myHeight" class="rightScroll" lock-x scrollbar-y ref="rightScroller" >
                
              
                <div  class="box2" style="padding:0px 0.5rem">
                  <div class="classifyImg"><img :src="getSanJiImg(detailClassify[0].data[0].image)" alt=""></div>
                  <div  class=""  ref="myGroup"  v-for="(item, i) in detailClassify" :key="i"> 
                    <p class="classifyTitle">{{item.name}}</p>
                    <div>
                        <flexbox :gutter="0" wrap="wrap" >
                          <flexbox-item :span="1/3" v-for="(classifyItem, index) in item.data" :key="index" @click.native="classifyClick(classifyItem.id,classifyItem.name)">
                            <div class="item_flexs">
                              <div class="item_flexsImg"><img :src="getSanJiImg(classifyItem.image)" alt=""></div>
                              <p ref="groupTitle">{{classifyItem.name}}</p>
                            </div>
                          </flexbox-item>
                        </flexbox>
                    </div>
                  </div>
                </div>
            </scroller>
          </div>
        </flexbox-item>
      </flexbox>

      <!-- 搜索界面 -->
      <div v-else>
        <classify-page :classifyData="classifyData"></classify-page>
      </div>
        <alert v-model="tankuang" :title="('提示')" @on-show="onShow" @on-hide="onHide">暂无数据</alert>

    
  </div>
</template>

<script>
import {
  Checker,
  XHeader,
  CheckerItem,
  Panel,
  XSwitch,
  Search,
  Group,
  Cell,
  Scroller,
  Flexbox,
  FlexboxItem,
  Divider,
  Grid,
  GridItem,
  GroupTitle,
  XInput,
  Alert
} from "vux";
import menu from "./menu.js";
import ExampleStart from "./ExampleStart";

import classifyPage from "../../components/toolComponent/classifyPage.vue";

import { homeUrl } from "../../components/utils/utils.js";

import $ from "jquery";
$(function() {
  $("#myGrid .weui-grid__icon").height($("#myGrid .weui-grid__icon").width());
});
import axios from "axios";
import qs from "qs";

export default {
  components: {
    classifyPage,
    Search,
    Group,
    Cell,
    ExampleStart,
    Scroller,
    Flexbox,
    FlexboxItem,
    Divider,
    Grid,
    GridItem,
    GroupTitle,
    XInput,
    Panel,
    XSwitch,
    Checker,
    CheckerItem,
    XHeader,
    Alert
  },
  watch: {
    $route: "getClassifyArr"
  },
  methods: {
    // 修改分类数据的结构
    modifyMinData(dataArr) {
      // 修改右侧小分类数据的结构
      if (dataArr.length <= 0) {
        return;
      }
      var resultArr = [];
      var previorName = dataArr[0].bigName;
      var tempDic = {};
      var minTempArr = [];
      for (var i = 0; i < dataArr.length; i++) {
        var data = dataArr[i];
        var bigName = data.bigName;
        var minName = data.minName;
        if (bigName != previorName) {
          tempDic["name"] = previorName;
          tempDic["datas"] = minTempArr;
          resultArr.push(tempDic);
          tempDic = {};
          minTempArr = [];
          previorName = bigName;
        } else {
          minTempArr.push(minName);
        }
      }
      this.$data.classifyArr = resultArr;
    },
    // 获取分类数据
    getClassifyArr() {
      // 获取分类数据
      this.$http.get(homeUrl() + "allBigFenlei/").then(
        result => {
          if (result.data.status == "ok") {
            console.log(result);
            this.leftData = result.data.data;
            this.onCellClick(this.leftData[0], 0);
            // 修改右侧分类数据的结构
            // this.modifyMinData(result.data.data)
          }
          // this.$vux.toast.text(result.data.message, 'bottom')
        },
        error => {
          this.$vux.toast.text("网络请求失败....", "bottom");
          console.log(error);
        }
      );
    },
    onItemClick(onItemClick) {
      var rs = {};
      console.log(onItemClick);
      this.isSearch = true;

      rs.title = onItemClick;
      rs.other = { data: onItemClick };
      this.results = onItemClick ? rs : [];

      this.searchData = JSON.stringify(rs);
    },
    setFocus() {
      this.$refs.search.setFocus();
    },
    resultClick(item) {
      this.$data.isSearch = true;
      console.log("llll");
      // console.log(JSON.stringify(item));
      this.searchData = JSON.stringify(item);
      // console.log(searchData)
    },
    getResult(val) {
      console.log("on-change", val);
      this.results = val ? getResults(this.value) : [];
      // console.log(getResults(this.value))
    },
    onSubmit() {
      this.$refs.search.setBlur();
      this.$vux.toast.show({
        type: "text",
        position: "top",
        text: "on submit"
      });
    },
     onHide() {
      console.log("on hide");
    },
    onShow() {
      console.log("on show");
    },
    onFocus() {
      console.log("on focus");
      this.$router.push({ name: "goSearch", params: {} });
    },
    onCancel() {
      this.$data.isSearch = false;
    },
    onScroll(event) {
      // console.log(this.$refs.myGroup[0].$el.getBoundingClientRect().height)
      var currentScrollTop = event.top;
      // console.log(this.$refs.groupTitle[0].$el.getBoundingClientRect().top)
      // var allGroup = this.$refs.myGroup;
      // var calHeight = 0;
      // for (var i = 0; i < allGroup.length; i++) {
      //   calHeight += allGroup[i].$el.getBoundingClientRect().height;
      //   if (currentScrollTop < calHeight - 100) {
      //     this.$data.currentLeftIndex = i;
      //     return;
      //   }
      // }
    },
    onCellClick(item, clickIndex) {
      console.log(item);
      var datas = qs.stringify({
        dafenleiId: item.id
      });
      axios
        .post(homeUrl() + "getAllFenleiByDafenleiId/", datas, {
          emulateJSON: false
        })
        .then(
          result => {
            console.log(result);
            if (result.data.status == "ok") {
              this.detailClassify = result.data.data;

              // this.getClassifyData(sanjiClass)
            }
          },
          error => {
            this.$vux.toast.text("网络请求失败....", "bottom");
            console.log(error);
          }
        );
      // var allGroup =  this.$refs.myGroup
      // var toTop = 0;
      // for (var i = 0; i < clickIndex; i++) {
      //   toTop += allGroup[i].$el.getBoundingClientRect().height;
      // }

      // this.$refs.rightScroller.reset({top:toTop , duration:1000})
      this.$data.currentLeftIndex = clickIndex;
    },
    // 三级分类
    getClassifyData(sanjiClass) {
      var classid = "";
      for (var i = 0; i < sanjiClass.length; i++) {
        classid = sanjiClass[i].id;
      }
      console.log(classid);
      // console.log(classifyData[0].fatherid)
      var datas = qs.stringify({
        fatherid: classid
      });
      axios
        .post(homeUrl() + "getSanjifenleiData/", datas, {
          emulateJSON: true
        })
        .then(
          result => {
            console.log(";;;;;;;;;;;;;;;;;;;;;;;;");
            console.log(result);
            if (result.data.status == "ok") {
              this.sanjiClassData = result.data.data;
            }
          },
          error => {
            this.$vux.toast.text("网络请求失败....", "bottom");
            console.log(error);
          }
        );
    },
    getSanJiImg(images) {
      if (images == undefined || images == "") {
        return ""
      }
      var shopImgs = homeUrl() + images;
      return shopImgs;
    },
    // 分类点击
    classifyClick(classifyId,classifyName) {
      console.log(classifyId);
      var datas = qs.stringify({
        minFenleiId: classifyId,
        page: 1
      });
      axios
        .post(homeUrl() + "getGoodsByMinfenleiId/", datas, {
          emulateJSON: true
        })
        .then(
          result => {
            // console.log("lalallalaalallaa");
            console.log(result.data.data);
            if(result.data.data.length==0){
            this.tankuang=true
              
            }else{
               var rs=[];
            rs.push(result.data.data);
             this.isSearch = true;
            this.classifyData = rs;
            console.log(rs)
            }
          },
          error => {
            this.$vux.toast.text("网络请求失败....", "bottom");
            console.log(error);
          }
        );
      // var rs = [];
      // rs.push({
      //   title: "小米6",
      //   other: "goodsname"
      // });

      // this.isSearch = true;
      // this.searchData = JSON.stringify(rs);
    }
  },
  created() {
    // 组件完成后获取数据,
    // 此时data已经被observed 了
    this.$vux.loading.show({
      text: "loading"
    });
    var that = this;
    setTimeout(() => {
      this.$vux.loading.hide();
    }, 1000);
    this.getClassifyArr();
  },
  mounted() {
    var windowHeight = $(window).height();
    var headerHeight = $(".vux-header").outerHeight();
    var searchBoxHeight = $(".vux-search-box").outerHeight();
    var tabHeight = $(".weui-tabbar").outerHeight();
    this.$data.myHeight =
      windowHeight - headerHeight - searchBoxHeight - tabHeight - 90 + "px";
  },
  data() {
    return {
      position: "default",
      showPositionValue: false,
      isSearch: false,
      results: [],
      value: "",
      classifyActive: [],
      myCols: 2,
      currentLeftIndex: 0,
      myHeight: "100px",
      classifyArr: [],
      classifyData: [],
      leftData: [],
      detailClassify: [],
      sanjiClassData: [],
      tankuang:false
    };
  },

  computed: {
    pageSections() {
      const flatten = (tree, level = 1) => {
        const treeCloned = JSON.parse(JSON.stringify(tree));
        let flattened = [];
        treeCloned.forEach(branch => {
          const { children } = branch;
          delete branch.children;
          branch.level = level;
          flattened.push(branch);
          if (children) {
            flattened = [...flattened, ...flatten(children, level + 1)];
          }
        });
        return flattened;
      };
      return flatten(menu);
    }
  }
};

function getResults(val) {
  var rs = [];
  var dataList = qs.stringify({
    queryStr: val,
    fieldName: "keywords"
  });
  axios
    .post(homeUrl() + "getGoodsBySomething/", dataList, { emulateJSON: true })
    .then(
      result => {
        console.log(result);
        var objArr = [];
        if (result.data.status == "ok") {
          objArr = result.data.data;
          console.log(objArr.length);
          for (var i = 0; i < objArr.length; i++) {
            rs.push({
              title: objArr[i],
              other: { data: objArr[i] }
            });
          }
          // console.log(".....")
        }
      },
      error => {
        this.$vux.toast.text("网络请求失败....", "bottom");
        console.log(error);
      }
    );
  return rs;
}
</script>
<style lang="less" >
#sets {
  width: 100%;
  z-index: 1000000;
  position: absolute;
  top: 0px;
}
.contentWrap {
  margin-top: 92px;
  // background: #ffffff;
}
/* 左侧滚动区域 */
.leftScroll {
  // background: red
}
.leftScroll .weui-cell .vux-label {
  color: #666;
}

#myrightGroup .weui-cells {
  margin-top: 0;
  // background-color: #F4F8FB
}
.classifyActive {
  // border: 1px solid orange;
  background: #ffffff !important;
  border-left: 5px solid #f74c31;
}
cell {
}
.grid-center {
  display: block;
  text-align: center;
  color: #666;
}
.grid-center img {
  width: 100%;
}

/* 分类界面 右边boder边线问题 */
#myGrid .weui-grid__icon {
  width: auto;
  height: 130px;
}
#myGrid .weui-grid__icon img {
  border-radius: 10px;
}
#myGrid::after {
  border-left: 0px;
}
#myGrid::before {
  border-top: 0px;
}
#myGrid .weui-grid::before {
  border-right: 0px;
}
#myGrid .weui-grid::after {
  border-bottom: 0px;
}
.item_flexs .item_flexsImg {
  // border: 1px solid red;
}
.item_flexs .item_flexsImg img {
  width: 100%;
  height: 70px;
}
.item_flexs p {
  text-align: center;
  font-size: 12px;
}
.item_flexs {
  padding: 8px;
}
.flexBoxWraps img {
  // background: #ffffff;
  // height: 100px;
}
.classifyImg {
  width: 100%;
  height: 100px;
}
.classifyImg img {
  width: 100%;
  height: 90px;
}
.rightScroll {
  background: #ffffff;
}
.leftContent {
  // background: #f74c31
}
.cells {
  background: #f4f4f4;
  border-bottom: none;
}
.classifyTitle {
  padding-left: 10px;
  font-weight: 700;
  line-height: 40px;
}
</style>
